package com.mumux.framework.aop.core;

import com.mumux.framework.aop.Invocation.CglibMethodInvocation;
import com.mumux.framework.aop.Invocation.MethodInvocation;
import com.mumux.framework.aop.advisor.TargetSource;
import com.mumux.framework.aop.interceptor.AopMethodInterceptor;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.List;

/**
  * @Author:huangjuncong
  * @Description: 这个类实现的 MethodInterceptor 是 gclib的接口，并非我们之前的 AopMethodInterceptor
  **/
public class DynamicAdvisedInterceptor implements MethodInterceptor{

    protected final List<AopMethodInterceptor> interceptorList;
    protected final TargetSource targetSource;

    public DynamicAdvisedInterceptor(List<AopMethodInterceptor> interceptorList, TargetSource targetSource) {
        this.interceptorList = interceptorList;
        this.targetSource = targetSource;
    }

    /**
     * 通过这行代码，我们的整个逻辑终于连起来了。也就是这个动态的拦截器，
     * 把我们通过 CglibMethodInvocation 织入了增强代码的方法，委托给了 cglib 来生成代理对象。
     * @param obj
     * @param method
     * @param args
     * @param proxy
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        MethodInvocation invocation = new CglibMethodInvocation(obj,targetSource.getTagetObject(),method, args,interceptorList,proxy);
        return invocation.proceed();
    }
}
